/**
 * 
 * @author hetao
 * js扩展工具类
 * 
 * 
 */

var sy = $.extend({}, sy);/* 全局对象 */

(function($) {

	/**
	 * 增加formatString功能
	 * 
	 * 使用方法：sy.fs('字符串{0}字符串{1}字符串','第一个变量','第二个变量');
	 */
	sy.fs = function(str) {
		for ( var i = 0; i < arguments.length - 1; i++) {
			str = str.replace("{" + i + "}", arguments[i + 1]);
		}
		return str;
	};

	/**
	 * 增加命名空间功能
	 * 
	 * 使用方法：sy.ns('jQuery.bbb.ccc','jQuery.eee.fff');
	 */
	sy.ns = function() {
		var o = {}, d;
		for ( var i = 0; i < arguments.length; i++) {
			d = arguments[i].split(".");
			o = window[d[0]] = window[d[0]] || {};
			for ( var k = 0; k < d.slice(1).length; k++) {
				o = o[d[k + 1]] = o[d[k + 1]] || {};
			}
		}
		return o;
	};

	/**
	 * 获得项目根路径	 * 
	 * 使用方法：sy.bp();
	 */
	sy.bp = function() {
		var curWwwPath = window.document.location.href;
		var pathName = window.document.location.pathname;
		var pos = curWwwPath.indexOf(pathName);
		var localhostPaht = curWwwPath.substring(0, pos);
		var projectName = pathName.substring(0, pathName.substr(1).indexOf('/') + 1);
		return (localhostPaht + projectName);
	};

	/**
	 * 对Date的扩展	 * 
	 * 将 Date 转化为指定格式的String
	 * 
	 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符
	 * 
	 * 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
	 * 
	 * (new Date()).pattern("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
	 * 
	 * (new Date()).pattern("yyyy-MM-dd E HH:mm:ss") ==> 2009-03-10 二 20:09:04
	 * 
	 * (new Date()).pattern("yyyy-MM-dd EE hh:mm:ss") ==> 2009-03-10 周二 08:09:04
	 * 
	 * (new Date()).pattern("yyyy-MM-dd EEE hh:mm:ss") ==> 2009-03-10 星期二 08:09:04
	 * 
	 * (new Date()).pattern("yyyy-M-d h:m:s.S") ==> 2006-7-2 8:9:4.18
	 */
	Date.prototype.pattern = function(fmt) {
		var o = {
			"M+" : this.getMonth() + 1, /* 月份 */
			"d+" : this.getDate(), /* 日 */
			"h+" : this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, /* 小时 */
			"H+" : this.getHours(), /* 小时 */
			"m+" : this.getMinutes(), /* 分 */
			"s+" : this.getSeconds(), /* 秒 */
			"q+" : Math.floor((this.getMonth() + 3) / 3), /* 季度 */
			/* 毫秒 */
			"S" : this.getMilliseconds()
		};
		var week = {
			"0" : "\u65e5",
			"1" : "\u4e00",
			"2" : "\u4e8c",
			"3" : "\u4e09",
			"4" : "\u56db",
			"5" : "\u4e94",
			"6" : "\u516d"
		};
		if (/(y+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
		}
		if (/(E+)/.test(fmt)) {
			fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "\u661f\u671f" : "\u5468") : "") + week[this.getDay() + ""]);
		}
		for ( var k in o) {
			if (new RegExp("(" + k + ")").test(fmt)) {
				fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
			}
		}
		return fmt;
	};

	/**
	 * IE6背景图片缓存
	 */
	try {
		document.execCommand("BackgroundImageCache", false, true);
	} catch (e) {
	}

	/**
	 * 生成UUID
	 */
	sy.UUID = function() {
		var s = [], itoh = '0123456789ABCDEF';
		for ( var i = 0; i < 36; i++)
			s[i] = Math.floor(Math.random() * 0x10);
		s[14] = 4;
		s[19] = (s[19] & 0x3) | 0x8;
		for ( var i = 0; i < 36; i++)
			s[i] = itoh[s[i]];
		s[8] = s[13] = s[18] = s[23] = '-';
		return s.join('');
	};
	
	//弹出窗口
	sy.showWindow = function(options){
		var title = options.title;
		var href = options.href == undefined ? null : options.href;
		var content = options.content;
		var width = options.width// > 770 ? options.width : 770;
		var height = options.height// > 580 ? options.height : 580;
		var type = options.type == undefined ? 1 : options.type;
		var buttons = [];
		if(buttons.length == 0) {
			buttons = null;
		}
		if(type == 1){
			$.get(href, {},function(str){
				 layer.open({
						type : type  ,
						title : title,
						shadeClose : false,
						moveOut:true,
						shade : 0.5,
						maxmin : true, //开启最大化最小化按钮
						area : [ width, height ],
						content : str,
						btn: ['提交', '取消'],
						yes:options.okhandler,
						chanel:options.cancelhandler
					});
				 initUI();
			});
		}else{
			layer.open({
				type : 2  ,
				title : title,
				shadeClose : false,
				moveOut:true,
				shade : 0.5,
				maxmin : true, //开启最大化最小化按钮
				area : [ width, height ],
				content : href,
				btn: ['提交', '取消'],
				yes:options.okhandler,
				chanel:options.cancelhandler
			});
		}
		
		 
	}
	
	sy.init = function (){
		toastr.options = {
				  "closeButton": true,
				  "debug": true,
				  "progressBar": true,
				  "positionClass": "toast-top-center",
				  "onclick": null,
				  "showDuration": "400",
				  "hideDuration": "1000",
				  "timeOut": "1000",
				  "extendedTimeOut": "1000",
				  "showEasing": "swing",
				  "hideEasing": "linear",
				  "showMethod": "fadeIn",
				  "hideMethod": "fadeOut"
				}

	}
	
	sy.msg = function (msg) {
		layer.msg(msg);
	}
	
	sy.toastrsAlert = function(obj){
		sy.init();
		if(obj.code == 'info'){
			 toastr.info(obj.msg, '提示');
		}else if(obj.code == 'warning'){
			 toastr.warning(obj.msg, '警告');
		}else if(obj.code == 'error'){
			 toastr.error(obj.msg, '失败');
		}else if(obj.code == 'success'){
			  toastr.success(obj.msg, '成功');
		}
       
	}
	
	/*sy.toastrs.info = function(content){
		sy.init();
        toastr.info(content, '提示');
	}
	sy.toastrs.warning = function(content){
		sy.init();
        toastr.warning(content, '警告');
	}
	sy.toastrs.error = function(content){
		sy.init();
        toastr.error(content, '失败');
	}*/
	
	//关闭弹出窗口
	sy.closeWindow = function(){
		 layer.closeAll();
	}
	
	
	sy.confirm = function confirm(dowork){
		layer.confirm('是否继续操作?', {icon: 3, title:'提示'}, function(index){
		    //do something
			dowork();
			layer.close(index);
		});
	}
	
	sy.reloadDiv = function (url){
		var o = layer.load();
			 $('.J_box[data-id="' + url + '"]').html('<div class="loading">加载中,请稍等。。<div>');
   		     $('.J_box[data-id="' + url + '"]').loadUrl(url,'get',{},function(data) {
				layer.close(o);
				$('.J_box[data-id="' + url + '"]').find("div.loading").remove();
			}); 
	}
	
	 
	$.ajaxSetup({
		cache : false,
		timeout : 5000
	});
})(jQuery);

 
 (function() {
	var oldajaxfuc = jQuery.ajax;
	jQuery.extend({
		ajax: function( url, options ){
			// If url is an object, simulate pre-1.5 signature
			if ( typeof url === "object" ) {
				options = url;
				url = undefined;
			}
			var oldSuccessFunc = options.success;
			options.success = function(ret) {
				var res = ret;
				var json = IN.jsonEval(ret);
				console.info(json);
				try {
					if(options.dataType == 'html'){
						res = $.parseJSON(ret);
					} 
				} catch (e) {
					// TODO: handle exception
				}
				if(json.sessionTimeout) {
					options.dataType ='json';
					 layer.confirm('登录已超时，请重新登录', {icon: 3, title:'提示'}, function(index){
						 location.href="login.action";
						});
				} else if(res.error) {
					options.dataType ='json';
					sy.msg(res.error);
				} else {
					if(res.noRight) {
						options.dataType ='json';
						sy.msg("没有权限！！");
					}
					oldSuccessFunc.apply(this, arguments);
				}
			};
			options.error = function(XMLHttpRequest, textStatus, errorThrown) {
				if('parsererror' == textStatus) {
					sy.msg(XMLHttpRequest.responseText);
					$.messager.show({
						title:'提示',
						msg:XMLHttpRequest.responseText,
						timeout:3000,
						showType:'slide'
					});
				} else if('timeout' == textStatus) {
					sy.msg("对不起，请求超时，请检查您的网络。");
				} else if('error' == textStatus) {
					sy.msg('error:'+XMLHttpRequest.responseText);
					 
				} else if('notmodified' == textStatus) {
					sy.msg(textStatus+errorThrown);
				}
			};
			oldajaxfuc(url, options);
		}
	});
})();
  
$(function() {
	
	//$(document.body).append('<div id="_AJAXLOADINGDIV_" style="z-index: 9999999; position: absolute; top: 0px; right: 0px; background-color:#FFFEE6; color:#8F5700; padding:5px;"><div>加载中……</div></div>');
	
	/**
	 * 显示AJAX开始时的提示信息	 */
	sy.showLoadingDiv = function() {
		$('#_AJAXLOADINGDIV_').show();
	};
	
	/**
	 * AJAX结束时隐藏提示信息	 */
	sy.hideLoadingDiv = function() {
		$('#_AJAXLOADINGDIV_').fadeOut(500);
	};
	
	/**
	 * 为jQuery的ajax提供等待提示
	 */
	//$(document).ajaxStart(sy.showLoadingDiv).ajaxStop(sy.hideLoadingDiv);
	
	/**
	 * 修改后台地址
	 */
	/*
	$.ajaxPrefilter( function( options ) {
		var url = options.url;
		if(url.indexOf("?") != -1) {
			url = url.substring(0, url.indexOf("?"));
		}
		if(url.search(/\.do$/) != -1) {
			options.url = "/farmer/" + options.url;
		}
	});
	*/
	
	// 图片预览
	$("a.imagePreview").each(function() {
		$this = $(this);
		$this.qtip({
			content: '<img src="' + $this.attr("href") + '?timestamp=' + (new Date()).valueOf() + '" />',
			style: {
				width: "auto",
				padding: "1px"
			}
		});
	})
	
});